package org.dromara.javalin.handler;

import cn.dev33.satoken.annotation.*;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.annotation.AnnotationUtil;
import io.javalin.http.Context;
import io.javalin.http.Handler;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;

public class SaTokenCheckHandler implements Handler {

    private final Method method;
    private final Handler next;

    public SaTokenCheckHandler(Method method, Handler next) {
        this.method = method;
        this.next = next;
    }

    @Override
    public void handle(@NotNull Context ctx) throws Exception {
        SaIgnore saIgnore = AnnotationUtil.getAnnotation(method, SaIgnore.class);
        if(saIgnore!=null){
            return;
        }
        SaCheckLogin saCheckLogin = AnnotationUtil.getAnnotation(method, SaCheckLogin.class);
        if(saCheckLogin!=null){
            StpUtil.checkLogin();
        }
        SaCheckPermission saCheckPermission = AnnotationUtil.getAnnotation(method, SaCheckPermission.class);
        if(saCheckPermission!=null){
            SaMode saMode = saCheckPermission.mode();
            if(SaMode.AND.equals(saMode)){
                StpUtil.checkPermissionAnd(saCheckPermission.value());
            }else {
                StpUtil.checkPermissionOr(saCheckPermission.value());
            }
        }
        SaCheckRole saCheckRole = AnnotationUtil.getAnnotation(method, SaCheckRole.class);
        if(saCheckRole!=null){
            SaMode saMode = saCheckRole.mode();
            if(SaMode.AND.equals(saMode)){
                StpUtil.checkRoleAnd(saCheckRole.value());
            }else {
                StpUtil.checkRoleOr(saCheckRole.value());
            }
        }
        next.handle(ctx);
    }
}
